(() => {
  try {
    const mp4s = new Set();
    const m3u8s = new Set();
    const push = (u) => {
      try {
        if (!u) return;
        const s = String(u);
        if (/^\/\//.test(s)) { mp4s.add('https:' + s); return; }
        if (/\.m3u8(\b|\?|#)/i.test(s)) m3u8s.add(s);
        else if (/\.(mp4|mov|webm)(\b|\?|#)/i.test(s)) mp4s.add(s);
      } catch {}
    };
    const walk = (obj, depth = 0) => {
      if (!obj || depth > 4) return;
      if (typeof obj === 'string') { push(obj); return; }
      if (Array.isArray(obj)) { for (const it of obj) walk(it, depth + 1); return; }
      if (typeof obj === 'object') {
        for (const k in obj) {
          try {
            const v = obj[k];
            if (k && /url|play|video|h264|mp4|source|src/i.test(k)) push(v);
            walk(v, depth + 1);
          } catch {}
        }
      }
    };
    const globals = [
      (window.__INITIAL_STATE__ || {}),
      (window.__APOLLO_STATE__ || {}),
      (window.__SSR_DATA__ || {}),
      (window.__XHS_GLOBAL__ || {}),
    ];
    try {
      const ld = document.querySelector('script[type="application/ld+json"]');
      if (ld && ld.textContent) globals.push(JSON.parse(ld.textContent));
    } catch {}
    for (const g of globals) try { walk(g); } catch {}
    const ev = new CustomEvent('xhsd-video-urls', { detail: JSON.stringify({ mp4: Array.from(mp4s), m3u8: Array.from(m3u8s) }) });
    window.dispatchEvent(ev);
  } catch (e) {
    try { window.dispatchEvent(new CustomEvent('xhsd-video-urls', { detail: JSON.stringify({ mp4: [], m3u8: [], error: String(e && e.message || e) }) })); } catch {}
  }
})();
